﻿@model WeddingEventManagement_API.Invoice
@{
    ViewBag.Title = "Invoice #" + Model.InvoiceID;
    Layout = "";
    var InvoiceItems = Model.InvoiceItems.ToList();
    decimal subtotal = 0;
    decimal tax = Model.InvTaxRate / 100;
    decimal disc = Model.InvDiscountPercentage / 100;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />

    <title>@ViewBag.Title - @ViewBag.CompanyName</title>

    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <link href="@Url.Content("~/Content/foundation.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/icomoon/style.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/print.css")" rel="stylesheet" media="print" type="text/css" />

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body style="background: #999; overflow: auto; padding: 0.5in;">
    <div id="invoice">
    @using (Html.BeginForm("Save", "Invoice", FormMethod.Post))
    {
        @Html.HiddenFor(model => model.InvoiceID)
        @Html.HiddenFor(model => model.Notes)
        @Html.HiddenFor(model => model.DueDate)

        <aside id="invoice-tools" class="noPrint">
            <div id="wrapper" class="twelve column">
                @*<a href="#" id="backBtn" class="button secondary expand" style="text-align: left; margin-top: 20px;"><i class="icon-arrow-left-2" style="margin-right: 10px;"></i> Back</a>*@
                <a 	href="@Url.Action("Details", "Client", new {id=Model.Event.ClientID})#tab3" class="button 	secondary expand" style="text-align: left; 	margin-top: 20px;"><i class="icon-arrow-left-2" style="margin-right: 10px;"></i> Go to Client</a>
                <br />
                <a 	href="@Url.Action("Details", "Event", new {id=Model.Event.EventID }	)#tab3" class="button 	secondary expand" style="text-align: left; 	margin-top: 20px;"><i class="icon-arrow-left-2" style="margin-right: 10px;"></i> Go to Event</a>
                <h3>Options</h3>
                <div class="row">
                    @Html.LabelFor(model => model.InvTaxRate, "Tax Rate")
                    @Html.TextBoxFor(model => model.InvTaxRate, new { type = "number", @class = "percentageInput", step="any" }) <span>%</span>
                </div>

                <div class="row" style="position: relative">
                    @Html.LabelFor(model => model.InvDeliveryCharge, "Delivery Charge")
                    <span class="moneySpan">$</span> @Html.TextBoxFor(model => model.InvDeliveryCharge, new { type = "number", step="any", @class = "moneyInput" })
                </div>

                <div class="row" >
                    @Html.LabelFor(model => model.InvDiscountPercentage, "Discount Percentage")
                    @Html.TextBoxFor(model => model.InvDiscountPercentage, new { type = "number", step="any", @class = "percentageInput" }) <span>%</span>
                </div>

                <br>

                <div class="row">
                        <input class="success button expand" type="submit" value="Save" />
                        <button id="printButton" href="#" class="button expand" style="margin-top: 5px">Print</button>
                </div>
            </div>
        </aside>
        
        <div class="row">
            <div class="six columns">
                <img src="/Images/@ViewBag.CompanyLogo" />
                <ul class="no-bullet">
                    <li><strong style="display: inline-block; width: 100px; ">Invoice #:</strong> @Model.InvoiceID</li>
                    <li><strong style="display: inline-block; width: 100px; ">Created:</strong> @Model.CreatedDate.ToShortDateString()</li>
                    <li><strong style="display: inline-block; width: 100px; ">Due:</strong> @Model.DueDate.ToShortDateString()</li>
                </ul>
            </div>
            <div class="six columns text-right">
                <p><strong>@ViewBag.CompanyName</strong></p>
                <address>
                    @ViewBag.CompanyAddress
                    <br>
                    @ViewBag.CompanyCity<text>,</text>
                    @ViewBag.CompanyProvince
                    @ViewBag.CompanyPostal
                </address>
                <p>
                    @ViewBag.CompanyPhone
                    <br>
                    @ViewBag.CompanyEmail
                </p>
            </div>
        </div>
        <div class="row">
            <div class="six columns">
                <h4 class="sub-title">Client</h4>
                <div>
                    <strong>@Model.Event.Client.FirstName @Model.Event.Client.LastName</strong>
                    <address>
                        @Model.Event.Client.Address
                        <br>
                        @Model.Event.Client.City<text>,</text>
                        @Model.Event.Client.Provence
                        @Model.Event.Client.PostalCode
                    </address>
                    <p>@Model.Event.Client.Email</p>
                </div>
            </div>
            <div class="six columns">
                <h4 class="sub-title">Event</h4>
                <div>
                    <strong>@Model.Event.Title</strong>
                    <address>
                        @Model.Event.StartDate.ToLongDateString() @Model.Event.StartDate.ToShortTimeString()
                    </address>
                    <p>
                        @Model.Event.EventType.EventTypeName
                    </p>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="twelve columns">
                <table cellspacing="0" cellpadding="0" class="table table-striped">
                    <thead>
                        <tr>
                            <th class="table-actions"></th>
                            <th class="border-left">Item</th>
                            <th>Description</th>
                            <th>Qty</th>
                            <th>Price</th>
                            <th class="no-border">Total</th>
                            <th class="table-actions"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <input id="itemCount" type="hidden" value="@InvoiceItems.Count" />
                        <input id="taxRate" type="hidden" value="@tax" />
                        <input id="discRate" type="hidden" value="@disc" />
                        <input id="deliveryCharge" type="hidden" value="@Model.InvDeliveryCharge" />

                        @for (int i = 0; i < InvoiceItems.Count; i++)
                        {
                            subtotal += InvoiceItems[i].Qty * InvoiceItems[i].Price;
                            <tr>
                                @Html.HiddenFor(x => InvoiceItems[i].Name)
                                @Html.HiddenFor(x => InvoiceItems[i].Price)
                                @Html.HiddenFor(x => InvoiceItems[i].Qty)
                                @Html.HiddenFor(x => InvoiceItems[i].Description)
                                @Html.HiddenFor(x => InvoiceItems[i].InvoiceItemID)
                                <td class="table-actions"><i class="icon-plus-2 has-tip tip-left row-add" title="Add New Row"></i></td>
                                <td contenteditable data-name="InvoiceItems[@i].Name" class="border-left">@InvoiceItems[i].Name</td>
                                <td contenteditable data-name="InvoiceItems[@i].Description">@InvoiceItems[i].Description</td>
                                <td contenteditable data-name="InvoiceItems[@i].Qty">@InvoiceItems[i].Qty</td>
                                <td contenteditable data-name="InvoiceItems[@i].Price">@InvoiceItems[i].Price.ToString("c").Replace("," ,"")</td>
                                <td class="total-col">@( (InvoiceItems[i].Qty * InvoiceItems[i].Price).ToString("c").Replace("," ,""))</td>
                                <td class="table-actions"><i class="icon-cancel-2 has-tip row-del" title="Delete Row"></i></td>
                            </tr>
                        }

                        <tr class="total-row bold-row">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Subtotal:</td>
                            <td id="subTotal" class="grand-col">@subtotal.ToString("c").Replace("," ,"")</td>
                            <td class="table-actions"></td>
                        </tr>

                        @{
                            decimal totalWithoutDiscount = subtotal + Model.InvDeliveryCharge;
                            decimal discount = totalWithoutDiscount * (disc);
                            decimal totalWithoutTax = totalWithoutDiscount - discount;
                            decimal totalTax = totalWithoutTax * tax;
                            decimal grandTotal = totalWithoutTax + totalTax;
                        }

                        <tr class="total-row">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Delivery Charge:</td>
                            <td id="delivery" class="grand-col">@Model.InvDeliveryCharge.ToString("c").Replace("," ,"")</td>
                            <td class="table-actions"></td>
                        </tr>

                        <tr class="total-row bold-row" style="display: @(Model.InvDiscountPercentage <= 0 ? "none" : "table-row")">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Total (without Discount):</td>
                            <td id="totalWithoutDiscount" class="grand-col">@((totalWithoutDiscount).ToString("c").Replace("," ,""))</td>
                            <td class="table-actions"></td>
                        </tr>

                        <tr class="total-row" style="display: @(Model.InvDiscountPercentage <= 0 ? "none" : "table-row")">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Discount (@Model.InvDiscountPercentage%):</td>
                            <td id="discountTotal" class="grand-col">@((discount).ToString("c").Replace("," ,""))</td>
                            <td class="table-actions"></td>
                        </tr>

                        <tr class="total-row bold-row">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Total (without Tax):</td>
                            <td id="totalWithoutTax" class="grand-col">@((totalWithoutTax).ToString("c").Replace("," ,""))</td>
                            <td class="table-actions"></td>
                        </tr>

                        <tr class="total-row ">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Tax (@Model.InvTaxRate%):</td>
                            <td id="taxTotal" class="grand-col">@((totalTax).ToString("c").Replace("," ,""))</td>
                            <td class="table-actions"></td>
                        </tr>

                        <tr class="total-row bold-row">
                            <td class="table-actions"></td>
                            <td class="" colspan="3"></td>
                            <td class="text-right">Grand Total:</td>
                            <td id="grandTotal" class="grand-col">@((grandTotal).ToString("c").Replace("," ,""))</td>
                            <td class="table-actions"></td>
                        </tr>

                    </tbody>
                </table>
            </div>
            <div class="row">
                <div class="twelve columns">
                    <hr />
                    <strong>Notes</strong>
                    <p contenteditable>@Model.Notes</p>
                </div>
            </div>
        </div>
    }

    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryUI")
    @Scripts.Render("~/Scripts/foundation.min.js")
    @Scripts.Render("~/Scripts/jquery.timeago.js")
    @Scripts.Render("~/Scripts/app.js")
    @Scripts.Render("~/Scripts/notifier.js")

    <script type="text/javascript">
        var unsavedChanges = false;

        var counter = $('#itemCount').val();
        var taxRate = $('#taxRate').val();
        var discRate = $('#discRate').val();
        var deliveryCharge = $('#deliveryCharge').val();

        var $subtotal = $('#subTotal');
        var $totalWithoutDiscount = $('#totalWithoutDiscount');
        var $discountTotal = $('#discountTotal');
        var $totalWithoutTax = $('#totalWithoutTax');
        var $taxtotal = $('#taxTotal');
        var $grandtotal = $('#grandTotal');

        window.onbeforeunload = function () {
            if (unsavedChanges)
                return 'You have unsaved changes!';
        }

        $('form').submit(function(){
            unsavedChanges = false;
        });

        $("#backBtn").click(function () {
            var url = document.referrer;
            window.location.href = url;
        });

        $('#printButton').click(function () {
            window.print();
            return false;
        });

        // Select All on Editable TD click
        $('#invoice .table').on('click', '[contenteditable]', function () {
            document.execCommand('selectAll', false, null);
        });

        // Add Row
        $('#invoice .table').on("click", ".row-add", function () {
            var $row = $(this).parent().parent();
            var HTML = NewRow(counter);
            $(HTML).insertAfter($row);
            counter++;

            unsavedChanges = true;
        });

        // Delete Row
        $('#invoice .table').on("click", ".row-del", function () {
            if (counter == 1) {
                alert("Must have at least one item");
                return;
            }

            var row = $(this).parent().parent();
            row.slideUp();

            $('td.total-col').trigger('change');

            row.find('input[name*="InvoiceItemID"]').val(-1);

            unsavedChanges = true;
        });

        // Update Hidden Field
        $('#invoice').on("focusout", "[contenteditable]", function () {
            var $this = $(this);
            var name = $this.data('name');
            var $hidden = $('input[name="' + name + '"]');
            var sanitizedInput = sanitizeInput($this.text(), name);

            // Set Text
            $this.text(sanitizedInput);

            // Set Val
            $hidden.val(sanitizedInput.replace('$', ''));

            if (name.indexOf('Qty') !== -1) {
                updateTotal($hidden, $this.siblings('input[name*="Price"]'), $this.siblings('td.total-col'));
            }
            else if (name.indexOf('Price') !== -1) {
                updateTotal($this.siblings('input[name*="Qty"]'), $hidden, $this.siblings('td.total-col'));
            }
        });

        // New Row Function
        function NewRow(id) {
            var string = '<tr><input type="hidden" name="InvoiceItems[$$].Name" value="" /><input type="hidden" name="InvoiceItems[$$].Price" value="" /><input type="hidden" name="InvoiceItems[$$].Qty" value="" /><input type="hidden" name="InvoiceItems[$$].Description" value="" /><td class="table-actions"><i class="icon-plus-2 has-tip row-add" title="Add New Row"></i></td><td contenteditable data-name="InvoiceItems[$$].Name" class="border-left"></td><td contenteditable data-name="InvoiceItems[$$].Description" ></td><td contenteditable data-name="InvoiceItems[$$].Qty">0</td><td contenteditable data-name="InvoiceItems[$$].Price">$0.00</td><td class="total-col">$0.00</td><td class="table-actions"><i class="icon-cancel-2 has-tip row-del" title="Delete Row"></i></td></tr>';
            return string.replace(/\$\$/g, id);
        }

        // Update the row total
        function updateTotal($qty, $price, $total) {
            var total = parseInt($qty.val()) * parseFloat($price.val());

            if (isNaN(total))
                total = 0.0;

            $total.text("$" + parseFloat(total).toFixed(2));
            $total.trigger('change');
        }

        function sanitizeInput(data, elmName) {

            data = data.replace("$", "");

            // Qty
            if (elmName.indexOf('Qty') !== -1) {
                if (!isNumber(data)) {
                    data = 0;
                }
                else {
                    data = parseInt(data);
                }
            } else if (elmName.indexOf('Price') !== -1) {
                if (!isNumber(data)) {
                    data = "$0.00";
                }
                else {
                    data = "$" + ((parseFloat(data)).toFixed(2)).toString();
                }
            }

            return data.toString();
        }

        function isNumber(o) {
            return !isNaN(o - 0) && o != null;
        }

        $('#invoice .table').on('change', 'td.total-col', function () {
            calculateTotals();

            unsavedChanges = true;
        });

        function calculateTotals() {
            var subTotal = 0.0;

            // Calculate Subtotal (sum of all item totals)
            $('td.total-col').each(function () {
                var value = $(this).text().replace('$', '');
                subTotal += parseFloat(value);
            });
            $subtotal.text("$" + subTotal.toFixed(2));
            
            //Total without discount
            var totalWithoutDiscount = subTotal + parseFloat(deliveryCharge);
            $totalWithoutDiscount.text("$" + (totalWithoutDiscount).toFixed(2));

            //Discount total
            var discountTotal = totalWithoutDiscount * discRate;
            $discountTotal.text("$" + (discountTotal).toFixed(2));

            //Total without tax
            var totalWithoutTax = totalWithoutDiscount - discountTotal;
            $totalWithoutTax.text("$" + (totalWithoutTax).toFixed(2));

            //Tax total
            var taxTotal = totalWithoutTax * taxRate;
            $taxtotal.text("$" + (taxTotal).toFixed(2));

            //Grand Total
            var grandTotal = totalWithoutTax + taxTotal;
            $grandtotal.text("$" + (grandTotal).toFixed(2));
        }
    </script>

    @if (TempData["Notify"] != null)
    {
        if (TempData["NotifyType"] == MessageType.Success.ToString())
        {
            <script>
                Notifier.success("@TempData["Notify"]");
            </script>
        }
        else if (TempData["NotifyType"] == MessageType.Warning.ToString())
        {
            <script>
                Notifier.warning("@TempData["Notify"]");
            </script>
        }
        else
        {
            <script>
                Notifier.info("@TempData["Notify"]");
            </script>
        }
    }
</body>
</html>
